import javafx.util.Pair;


public class Solution19 {
    public static void main(String[] args) {
    }
    int[] rowDir =  {-1,-1,-1,0, 0,1,1, 1};
    int[] columnDir={ 0, 1,-1,-1,1,0,1,-1};
    int n;
    int m;
    public char[][] updateBoard(char[][] board, int[] click) {
        if(board ==null)return null;
        char clickChar = board[click[0]][click[1]];
        if( clickChar == 'M'){
            clickChar = 'X';
            return board;
        }
        //剩下的情况B/E，
        n=board.length;
        m=board[0].length;
        Pair<Integer,Integer> pair = new Pair<>(click[0],click[1]);
        _updateBoard(board,pair);
        return board;
    }

    private void _updateBoard(char[][] board,Pair<Integer,Integer> pair) {
        int count = isBlank(board,pair);
        if(count>0){
            board[pair.getKey()][pair.getValue()] = (char)(count+'0');
            return;
        }else{
            if(board[pair.getKey()][pair.getValue()] == 'B')return;
            board[pair.getKey()][pair.getValue()] = 'B';
            for(int i=0;i<rowDir.length;i++){
                if((pair.getKey()+rowDir[i])>=0&&(pair.getValue()+columnDir[i])>=0&& (pair.getKey()+rowDir[i])<n&&(pair.getValue()+columnDir[i])<m){
                    Pair<Integer,Integer> newPair = new Pair<>(pair.getKey()+rowDir[i],pair.getValue()+columnDir[i]);
                    _updateBoard(board,newPair);
                }
            }
        }
    }

    private int isBlank(char[][] board, Pair<Integer, Integer> pair) {
        int count = 0;
        for(int i=0;i<rowDir.length;i++){
            int row = pair.getKey()+rowDir[i];
            int column = pair.getValue()+columnDir[i];
            if(row>=0&&column>=0&& row<n&&column<m){
                if(board[row][column] == 'M')count++;
            }
        }
        return count;
    }


}
